"use strict";

const logger = log.getLogger("sdk");
const common = requireMod("common");
const commonService = requireService("common");

const jobs_path = getSysConfig("jobsPath");

const REPLACE_DATA = {
    "protocol": getSysConfig("protocol")
    ,"collectUrl": getSysConfig("collectUrl")
};

/**
 * 标准 sdk 构成列表
 * @type {Array}
 */
const ACTIVITY_SDK_JOBS = [
    "base"
    ,"collect-conf"
    ,"collect"
    ,"pageview"
    ,"click"
    ,"event"
    ,"share"
    ,"stay"
    ,"unload"
    ,"user"
    ,"collect-boot"
];

/**
 * 获取活动 sdk
 */
function onGetSdk(ctx) {
    if (!ctx.params.customer || !ctx.params.ent_id) {
        ctx.body = "";
        return;
    }

    var repData = {
        "protocol": REPLACE_DATA.protocol
        ,"collectUrl": REPLACE_DATA.collectUrl
        ,"customer": ctx.params.customer
        ,"ent_id": ctx.params.ent_id
    };

    // 替换设置中的索引标识
    repData.collectUrl = repData.collectUrl.replace(/pi-([\w\-]+)/, `pi-${ctx.params.customer}`);

    // 要加载的模块列表
    var mods = ACTIVITY_SDK_JOBS.slice(0, ACTIVITY_SDK_JOBS.length - 1);
    if (ctx.query.m) {
        // 追加指定的模块
        mods = mods.concat(ctx.query.m.split(","))
    }
    mods.push(ACTIVITY_SDK_JOBS[ACTIVITY_SDK_JOBS.length - 1]);

    var re = "";
    mods.forEach(file => {
        var dat = commonService.cache.get(file);
        if (!dat) {
            dat = commonService.read(jobs_path, file + ".js", logger);
            if (dat) {
                commonService.cache.set(file,dat);
            }
        }
        re += "\n" + dat;
    });

    var rData = common.merge(ctx.query, repData);
    re = common.labelReplace(re, rData);
    re = commonService.warpRespone(
        re
    );
    rData = null;

    commonService.setHeader.call(ctx);

    mods = null;
    ctx.body = re;
}


module.exports = {
    "@collect/:customer/:ent_id":["GET", onGetSdk]
}
